const express = require("express");
const jwt = require("jsonwebtoken");
const expressJwt = require("express-jwt");
const userService = require("../services/user");
const { secretKey } = require("../constant/constant");

let router = express.Router();

router.post("/login", async (req, res, next) => {
  try {
    const { username, password } = req.body;

    const result = await userService.read(username, password).then(function (result) {
      let content = { name: username }; // 要生成token的主题信息
      let token = jwt.sign(content, secretKey, {
        expiresIn: 60 * 60 * 1 * 24 // 24小时过期
      });

      // 为数据库中登录成功的账号添加token
      userService.modifyToken(username, token);

      const data = result && result[0];
      res.send({ code: 200, token: token, msg: "登录成功", data: data });
    }).catch(function (err) {
      res.send({ code: 500, token: "", msg: "登录失败", data: "" });
    }) ;

    // if (result.length != 0) {
    //
    // } else {
    //
    // }
  } catch (e) {
    next(e);
  }
});

router.post("/getUserInfo", async (req, res, next) => {
  try {
    const { username } = req.body;
    const result = await userService.getUserInfo(username);
    const data = result && result[0];
    res.send({ code: 200, msg: "请求成功", data: data });
  } catch (e) {
    next(e);
  }
});

router.post("/getRouteList", async (req, res, next) => {
  try {
    const { user_type } = req.body;
    const result = await userService.getRouteList(user_type);

    let data = [];
    result.forEach(item => {
      data.push(item.route);
    });
    console.log(data);
    res.send({ code: 200, msg: "请求成功", data: data });
  } catch (e) {
    next(e);
  }
});

// 获取路由菜单
router.post("/getUserMenu", async (req, res, next) => {
  try {
    const { user_type } = req.body;
    const menus = await userService.getRouters(0);
    const data = [];
    for (let i = 0; i < menus.length; i++) {
      let item = menus[i];
      let childList = await userService.getRouters(item.id);
      let menu = {
        id: item.id,
        path: item.path,
        level: item.level,
        name: item.name,
        p_id: item.p_id,
        icon: item.icon,
        route: item.route,
        user_type: item.user_type,
        children: childList
      };
      data.push(menu);
    }

    res.send({ code: 200, msg: "请求成功", data: data });
  } catch (e) {
    next(e);
  }
});

//获取动态表头
router.post("/getTestTable", async(req, res, next) => {

  res.send({code: 200, msg: "请求成功", data:""});
})

module.exports = router;
